<!DOCTYPE html>
<html>
<head>
	<title></title>
	<link rel="stylesheet" type="text/css" href="/bower_components/cropper/dist/cropper.css">
	<style type="text/css">
		img{
			max-width: 100%;
		}
	</style>
</head>
<body>
	<input type="file" name="" onchange="selectImage(this);">
	<div id='cp' style="width:50%;height:auto;">
		<!-- <img id="myimg" src=""> -->
	</div>
	
</body>
<script src="/bower_components/jquery/dist/jquery.js"></script>
<script src="/bower_components/cropper/dist/cropper.js"></script>
<script>
	var input = '';
	function selectImage(file) {
		if (!file.files || !file.files[0]) {
			return;
		}
        var reader = new FileReader();
		reader.onload = function (evt) {
			$('#cp').html('<img id="myimg" src="'+evt.target.result+'">'+
						  '<button class="btn">提交</button>')
			imageload()
			btnload()
			input = evt.target.result;
		}
		reader.readAsDataURL(file.files[0]);
    }
	function convertToData(url, canvasdata, cropdata, callback) {  
	    var cropw = cropdata.width; // 剪切的宽  
	    var croph = cropdata.height; // 剪切的宽  
	    var imgw = canvasdata.width; // 图片缩放或则放大后的高  
	    var imgh = canvasdata.height; // 图片缩放或则放大后的高

	    var poleft = canvasdata.left - cropdata.left; // canvas定位图片的左边位置  
	    var potop = canvasdata.top - cropdata.top; // canvas定位图片的上边位置  
	      
	    var canvas = document.createElement("canvas");  
	    var ctx = canvas.getContext('2d');  
	      
	    canvas.width = cropw;  
	    canvas.height = croph;  
	      
	    var img = new Image();  
	    img.src = url;  
	      
	    img.onload = function() {  
	        this.width = imgw;  
	        this.height = imgh;  
	        // 这里主要是懂得canvas与图片的裁剪之间的关系位置  
	        ctx.drawImage(this, poleft, potop, this.width, this.height);  
	        var base64 = canvas.toDataURL('image/jpg', 1);
	        callback && callback(base64)      // 回调base64字符串  
	    }  
	}  
	
	function imageload(){
		$image = $('#myimg');

		$image.on("load", function() {        // 等待图片加载成功后，才进行图片的裁剪功能  
			$image.cropper({  
				aspectRatio: 1 / 1,
				viewMode:2
			});  
		})
	}
	function btnload(){

		$(".btn").on("click", function() {  
			var src = $image.eq(0).attr("src");  
			var canvasdata = $image.cropper("getCanvasData");  
			var cropBoxData = $image.cropper('getCropBoxData');
			convertToData(src, canvasdata, cropBoxData, function(basechar) {
				console.log(basechar);
				$(".newImg").attr("src", basechar)
				$('.btn').after('<img class="newImg" src="'+basechar+'">')
		    });  
		})
	}
</script>
</html>